// 导包
import http from 'wechat-http'

// 配置请求基地址
http.baseURL = 'https://live-api.itheima.net'

// 请求拦截器
http.intercept.request = (options) => {
  const defaultHeader = {}
  // Authorization字段拼接到请求头上 值是token
  defaultHeader.Authorization = 'Bearer ' + getApp().token
  // 合并请求头信息
  options.header = Object.assign({}, defaultHeader, options.header)

  return options
}



// 响应拦截器
http.intercept.response = async (res) => {
  if (res.data.code === 401) {
    const app = getApp()
    // 状态为 401 且接口为 /refreshToken 表明 refreshToken 也过期了
    if (res.config.url.includes('/refreshToken')) {
      const pageStack = getCurrentPages()
      const currentPage = pageStack.pop()
      const redirectURL = currentPage.route
      return wx.redirectTo({
        url: '/pages/login/index?redirectURL=/' + redirectURL,
      })
    }
    const result = await http({
      url: '/refreshToken',
      method: 'post',
      header: {
        Authorization: 'Bearer ' + app.refreshToken
      }
    })
    if (result.code !== 10000) return wx.utils.toast('更新token失败')
    app.setToken('token', result.data.token)
    app.setToken('refreshToken', result.data.refreshToken)
    // 无感刷新
    res.config = Object.assign(res.config, {
      header: {
        Authorization: 'Bearer ' + result.data.token
      }
    })
    return http(res.config)
  }
  return res.data
}

// 导出模块方式
export default http
wx.http = http